<script setup lang="ts">
import { h, defineProps, defineEmits, computed } from 'vue'
import draggable from 'vuedraggable'
import DynamicRenderer from './render'
import type { LayoutFunction } from './type'
import { ElFormItem, ElCol, ElRow } from 'element-plus' // 正确导入 Element Plus 组件
import { Icon } from '@/components/Icon'
const props = defineProps<{
  element: any
  index: number
  drawingList: any[]
  activeId?: number | null
  formConf: any
}>()

const emit = defineEmits<{
  (e: 'copyItem', element: any, parent: any[]): void
  (e: 'deleteItem', index: number, parent: any[]): void
  (e: 'activeItem', element: any): void
  (e: 'update:elementValue', value: any): void
}>()

// 按钮组件
const itemBtns = (element: any, index: number, parent: any[]) => {
  return [
    h(
      'span',
      {
        class: 'drawing-item-copy',
        title: '复制',
        onClick: (event: Event) => {
          emit('copyItem', element, parent)
          event.stopPropagation()
        }
      },
      h(Icon, { icon: 'ep:copy-document', size: 12 })
    ),
    h(
      'span',
      {
        class: 'drawing-item-delete',
        title: '删除',
        onClick: (event: Event) => {
          emit('deleteItem', index, parent)
          event.stopPropagation()
        }
      },
      h(Icon, { icon: 'ep:delete', size: 12 })
    )
  ]
}

// 列表单项布局
const colFormItem: LayoutFunction = (element, index, parent) => {
  console.log(element)

  const className = computed(() => [
    'drawing-item',
    props.activeId === element.formId ? 'active-from-item' : '',
    props.formConf.unFocusedComponentBorder ? 'unfocus-bordered' : ''
  ])
  return h(
    ElCol,
    {
      span: element.span,
      class: className.value,
      onClick: (event: Event) => {
        emit('activeItem', element)
        event.stopPropagation()
      }
    },
    [
      h(
        ElFormItem,
        {
          labelWidth: element.labelWidth ? `${element.labelWidth}px` : undefined,
          label: element.label,
          required: element.required
        },
        h(DynamicRenderer, {
          key: element.renderKey,
          conf: element,
          modelValue: element.defaultValue, // 确保传递当前值
          'onUpdate:modelValue': (value: any) => {
            element.defaultValue = value // 更新值
            emit('update:elementValue', value)
          }
        })
      ),
      ...itemBtns(element, index, parent)
    ]
  )
}

// 行表单项布局
const rowFormItem: LayoutFunction = (element, index, parent) => {
  const className = computed(() => [
    'drawing-row-item',
    props.activeId === element.formId ? 'active-from-item' : ''
  ])

  let child: any = renderChildren(element.children || [])

  if (element.type === 'flex') {
    child = h(
      ElRow,
      {
        type: element.type
      },
      child
    )
  }

  return h(
    ElCol,
    {
      span: element.span
    },
    h(
      ElRow,
      {
        gutter: element.gutter,
        class: className.value,
        onClick: (event: Event) => {
          emit('activeItem', element)
          event.stopPropagation()
        }
      },
      [
        h('span', { class: 'component-name' }, element.componentName),
        h(
          draggable,
          {
            list: element.children,
            animation: 340,
            group: 'componentsGroup',
            class: 'drag-wrapper',
            itemKey: 'formId'
          },
          { default: () => child }
        ),
        ...itemBtns(element, index, parent)
      ]
    )
  )
}

// 渲染子元素
const renderChildren = (children: any[] = []): any[] => {
  return children.map((el, i) => {
    const layout = layouts[el.layout || '']
    if (layout) {
      return layout(el, i, children)
    }
    return layoutIsNotFound()
  })
}

// 布局未找到处理
const layoutIsNotFound = (): never => {
  throw new Error('没有匹配的layout')
}

// 布局映射
const layouts: Record<string, LayoutFunction> = {
  colFormItem,
  rowFormItem
}

// 主渲染函数
const renderLayout = () => {
  const layout = layouts[props.element.layout || '']
  if (layout) {
    return layout(props.element, props.index, props.drawingList)
  }
  console.log(layoutIsNotFound)

  return layoutIsNotFound()
}
</script>

<template>
  <renderLayout />
</template>

<style scoped>
:deep(.el-row .center-board-row) {
  margin: 0 !important;
}
.drawing-item {
  margin-bottom: 15px;
  border: 1px solid white;
  border-radius: 4px;
  transition: all 0.3s;
  position: relative;

  &.active-from-item {
    /* border-color: #409eff; */
    /* box-shadow: 0 0 8px rgba(64, 158, 255, 0.2); */
  }

  &.unfocus-bordered {
    border: 1px dashed #ccc;
  }
}

.drawing-row-item {
  padding: 0 2px;
  margin-bottom: 15px;
  border: 1px dashed #ccc;
  border-radius: 3px;
  position: relative;

  &.active-from-item {
    border: 1px dashed #409eff;
  }
}
.drawing-item :deep(.el-form-item) {
  padding: 12px 10px;
  margin-bottom: 0px;
}
.component-name {
  font-size: 12px;
  color: #bbb;
  padding: 0 6px;
}

.drag-wrapper {
  min-height: 80px;
  padding: 5px;
}

:deep(.drawing-item-copy),
:deep(.drawing-item-delete) {
  position: absolute;
  top: -10px;
  width: 18px;
  height: 18px;
  line-height: 18px;
  text-align: center;
  border-radius: 50%;
  font-size: 12px;
  border: 1px solid;
  cursor: pointer;
  z-index: 1;
}

:deep(.drawing-item-copy) {
  right: 56px;
  border-color: #409eff;
  color: #409eff;
  background: #fff;

  &:hover {
    background: #409eff;
    color: #fff;
  }
}

:deep(.drawing-item-delete) {
  right: 24px;
  border-color: #f56c6c;
  color: #f56c6c;
  background: #fff;

  &:hover {
    background: #f56c6c;
    color: #fff;
  }
}
</style>
